﻿using Microsoft.Xrm.Sdk;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace isky.Plugin
{
    public class UpdateAccountCreditlimit : IPlugin
    {
        /// <summary>
        /// 修改客户信用额度
        /// </summary>
        /// <param name="serviceProvider"></param>
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context service from the service provider.
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            // Obtain the Organization Service factory service from the service provider
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            var service = factory.CreateOrganizationService(context.UserId);
            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity inputEntity = context.InputParameters["Target"] as Entity;
                   // Entity preImageEntity = (context.PreEntityImages != null && context.PreEntityImages.Contains("PreImage")) ? context.PreEntityImages["PreImage"] : null;
                    if (inputEntity.Id == Guid.Empty)
                    {
                        return;
                    }

                    if (inputEntity.Contains("creditlimit"))
                    {
                        Entity entity = new Entity();
                        entity.Id = context.PrimaryEntityId;
                        entity.LogicalName = context.PrimaryEntityName;
                        float accountcreditlimit = 100000000;
                        inputEntity.Attributes["creditlimit"] = accountcreditlimit;
                        service.Update(entity);
                    }
                 
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
                throw new NotImplementedException();
            }
        }
    }
}
